#include "StoredAnimationNode.h"
#include "TimedRotation.h"
#include "SkeletonNode.h"

#include <algorithm>

StoredAnimationNode::StoredAnimationNode(tstring name) : AnimationNode(name),m_IsControlled(false),
	m_IsConnectedToController(false)
{
}


StoredAnimationNode::StoredAnimationNode(tstring name,bool isControlled,bool isConnectedToController) : 
	AnimationNode(name),
	m_IsControlled(isControlled),
	m_IsConnectedToController(isConnectedToController)
{
}

StoredAnimationNode::~StoredAnimationNode(void)
{
}


void StoredAnimationNode::AddTransformAt(int time, DAEFloat4 rotation,DAEFloat3 pivot)
{
	TimedRotation tr(time,rotation,pivot,DAEFloat3(1,1,1));
	m_Rotations.push_back(tr);

	std::sort(m_Rotations.begin(),m_Rotations.end(),TimedRotationSorter());
}

void StoredAnimationNode::AddTransformAt(int time, DAEFloat3 rotation,DAEFloat3 pivot,DAEFloat3 scale){
	DAEFloat4 rot4(rotation.x,rotation.y,rotation.z,0);
	TimedRotation tr(time,rot4,pivot,scale);
	m_Rotations.push_back(tr);

	std::sort(m_Rotations.begin(),m_Rotations.end(),TimedRotationSorter());
}

void StoredAnimationNode::AddTransformAt(int time, DAEFloat4 rotation, DAEFloat3 pivot,DAEFloat3 scale)
{
	TimedRotation tr(time,rotation,pivot,scale);
	m_Rotations.push_back(tr);
	std::sort(m_Rotations.begin(),m_Rotations.end(),TimedRotationSorter());
}

const bool StoredAnimationNode::GetTransformAt(float time,DAEFloat4& rotation, DAEFloat3& pivot,DAEFloat3& scale)const
{
	unsigned int t = static_cast<unsigned int>(time);
	TimedRotation tr(t);
	vector<TimedRotation>::const_iterator it;
	// use binary search
	it = std::lower_bound(m_Rotations.begin(),m_Rotations.end(),tr,TimedRotationSorter());
	if ( it != m_Rotations.end()){
		rotation = (*it).GetRotation();
		pivot = (*it).GetPivot();
		scale = (*it).GetScale();
		return true;
	}else
		return false;
}

const bool StoredAnimationNode::GetTransformAt(float time, DAEMatrix& deltaTrans, DAEMatrix& matrix)
{
	unsigned int t = static_cast<unsigned int>(time);
	TimedRotation tr(t);
	vector<TimedRotation>::const_iterator it;
	// use binary search
	it = std::lower_bound(m_Rotations.begin(),m_Rotations.end(),tr,TimedRotationSorter());
	if ( it != m_Rotations.end()){
		DAEFloat4 rotation = (*it).GetRotation();
		DAEFloat3 pivot = (*it).GetPivot();
		DAEFloat3 scale = (*it).GetScale();
		TRSTransform trs;
		trs.SetRotation(rotation.x,rotation.y,rotation.z);
		trs.SetTranslation(pivot.x,pivot.y,pivot.z);
		trs.SetScale(scale.x,scale.y,scale.z);
		DAEMatrix anim = trs.GetCompiledMatrix();
		matrix.SetValues(anim);
		return true;
	}else
		return false;
}
